This was the question from codewars:
Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').
Examples:
And this is what i have achieved:
function solution(str) {
const letters = str.split('');
let text = '';
for (const letter of letters) {
text += letter;
if (text.replace(/ /g, '').length % 2 === 0)
letter !== letters[letters.length - 1] && (text += ' ');
}
if (str.length % 2 !== 0) text += '_';
return text.split(' ');
}
console.log(solution('abcd'));
This is the error, i'm getting: expected [ '' ] to deeply equal []
function solution(str) {
const letters = str.split('');
let text = '';
for (const letter of letters) {
text += letter;
if (text.replace(/ /g, '').length % 2 === 0)
letter !== letters[letters.length - 1] && (text += ' ');
}
if (str.length % 2 !== 0) text += '_';
console.log(text);
return (text === '' && []) || text.split(' ');
}
console.log(solution(''));
Now its working as expected when solution function is called as solution(' ') and now it returns an empty array [ ] instead of an array with an empty string[' ']